<template>
	<view>
		<base-common></base-common>
		<div class="backgrounCont">
			<div class="bind_stu">
				<p class="title_row">
					请使用
					<text style="color: #fd453d">报名手机号</text>
					查询
				</p>
				<!-- 姓名 -->
				<div
					class="name_row"
					:style="{
						display: feedbackData && feedbackData.studentName ? 'block' : 'none'
					}"
				>
					<div
						style="
							position: relative;
							border-bottom: 1px solid #ececec;
							margin-top: 23%;
							font-size: 32rpx;
						"
					>
						<text>{{ username }}</text>
						<!-- <view v-if="username" class="clear_name iconfont icon-close" color="#999999" ref="clearName" @click="clearName" ></view> -->
					</div>
				</div>
				<!-- 手机号输入 -->
				<div class="name_row">
					<div style="position: relative; border-bottom: 1px solid #ececec">
						<input
							ref="mobile"
							:style="{
								marginTop: feedbackData && feedbackData.studentName ? 0 : '23%'
							}"
							v-model="mobile"
							class="username"
							maxlength="11"
							type="number"
							placeholder="请输入报名手机号"
							@input="changeName($event)"
						/>
						<view
							v-if="mobile"
							class="clear_name iconfont icon-close"
							color="#999999"
							ref="clearName"
							@click="clearName"
						></view>
					</div>
					<p class="tit_text" ref="name_tit">
						{{ mobileCode ? '请正确填写手机号码！' : '' }}
					</p>
				</div>
				<!-- 填写验证码 获取验证码 -->
				<div class="pwd_row">
					<div style="position: relative; border-bottom: 1px solid #ececec">
						<!-- 让改5位验证码长度 -->
						<input
							ref="verifyCode"
							v-model="verifyCode"
							class="password"
							type="number"
							placeholder="请输入验证码"
							maxlength="5"
						/>
						<!-- <view v-if="verifyCode" class="clear_pwd iconfont icon-close" color="#999999" ref="clearPwd" @click="clearPwd" ></view> -->
						<text
							class="get_code"
							:style="{ color: mobileCode ? '#ccc' : '#FD453D' }"
							@click="getVerify"
						>
							{{ show ? '获取验证码' : count + 's' }}
						</text>
					</div>
					<p class="tit_text" ref="pwd_tit">{{ errorVerify }}</p>
				</div>

				<div
					class="add_btn"
					:style="{ background: addStudentFlag ? '#FD453D' : '#ccc' }"
					@click="addStudentCode"
				>
					查询
				</div>
				<div class="prompt_copy" :style="{ marginTop: '15px', display: 'block' }">
					{{ tipText }}
				</div>
			</div>
		</div>
		<div v-if="status == 2" class="prompt-box">
			<div class="alert_prompt" ref="alertPop">
				<view class="iconfont icon-prompt prompt_icon"></view>
				<p class="prompt_text">{{ msg }}</p>
			</div>
		</div>
		<!-- <div class="jump-url" v-if="myInfo.userId">
			我是老师，<text class="url-link" @click="goBindEmail">点击这里</text>
		</div> -->
	</view>
</template>
<script>
import {
	apiBindStudentCode,
	apiGetUserInfo,
	apiAddStudentCode,
	apiSendVerificationCode,
	apiGetStudentListByPhone,
	apiAddBinding
} from '@/api/user/user.js'
import { mapActions } from 'vuex'
export default {
	name: 'IedpMaterialUiBindstudent',

	data() {
		return {
			status: 1,
			username: '', //名字
			mobile: '', //手机号
			mobileCode: false,
			errorVerify: '',
			verifyCode: '', //验证码
			msg: '',
			to: '',
			myInfo: {},
			backUrl: '', //课后反馈班级页面的地址以及参数
			feedbackData: '', //课后反馈 学员详情页需要的数据
			tipText: '', //提示文案
			timer: '', //验证码倒计时方法
			count: '', //验证码倒计时 秒数
			show: true, //验证码 隐藏显示文案开关
			allStudent: [],
			addStudentFlag: false, //禁止点击开关
			listenType: ''
		}
	},
	onLoad(option) {
		this.to = option.to
		this.listenType = option.listenType || ''
		console.log('this.to', option)
		// 此处是当前学员列表中没有班级反馈页面点击查看的学员 跳进绑定学员页 绑定
		if (option.studentName) {
			this.username = decodeURIComponent(option.studentName)
			this.backUrl = uni.getStorageSync('origin')
			uni.setStorageSync('origin', '')
			this.feedbackData = option
		}
	},
	watch: {
		verifyCode: {
			handler(newVal) {
				this.errorVerify = ''
			},
			deep: true
		}
	},
	created() {
		this.getUserInfo()
		// // 获取当前绑定的学员列表
		this.allStudent = []
	},

	methods: {
		...mapActions(['GetUserInfo']),
		//获取验证码
		getVerify() {
			if (this.mobileCode) {
				return
			}
			if (!this.show) {
				return
			}
			if (this.mobile.length != 11 || this.mobile.length == 0) {
				this.mobileCode = true
				return
			}
			this.addStudentFlag = true
			const TIME_COUNT = 60
			if (!this.timer) {
				this.count = TIME_COUNT
				this.show = false
				this.timer = setInterval(() => {
					if (this.count > 0 && this.count <= TIME_COUNT) {
						this.count--
					} else {
						this.show = true
						clearInterval(this.timer)
						this.timer = null
						// this.addStudentFlag=false
						this.tipText = ''
					}
				}, 1000)
			}
			// 发送短信
			apiSendVerificationCode({
				mobile: this.mobile
			}).then((res) => {
				console.log('打印验证码发送是否成功', res)
			})
			// console.log('获取学员列表',this.$store.getters.studentList)
		},
		changeName(e) {
			this.tipText = ''
			if (e.detail.value.length == 11) {
				if (!/^(((1[3,4,5,6,7,8,9][0-9]{1}))+\d{8})$/.test(this.mobile.trim())) {
					this.mobileCode = true
				} else {
					this.mobileCode = false
					this.addStudentFlag = true //允许点查询按钮
				}
			} else {
				this.addStudentFlag = false //禁止点查询按钮
			}
			if (e.detail.value.length == '') {
				this.mobileCode = false
			}
		},
		clearName() {
			this.mobile = ''
			this.mobileCode = false
			this.addStudentFlag = false
		},
		clearPwd() {
			this.verifyCode = ''
			this.errorVerify = ''
		},
		addStudentPort(studentName, studentCode) {
			let preData = {
				name: studentName,
				code: studentCode
			}
			apiAddStudentCode(preData)
				.then((res) => {
					if (res.code == 200) {
						this.$cache.delete('_NodeWords')
						this.$cache.delete('_CurrentWordIndex')
						this.$store.dispatch('initStudy', {
							reviewTotal: 0,
							studyReview: 0,
							newTotal: 0,
							studyNews: 0,
							studyTime: 0
						})
						uni.setStorageSync('studentCode', preData.code + new Date().getTime())
						uni.showToast({
							title: '绑定成功',
							icon: 'success'
						})

						let oldArr = uni.getStorageSync('bindList') || []
						if (!oldArr.includes(this.myInfo.userId)) {
							oldArr.push(this.myInfo.userId)
						}
						uni.setStorageSync('bindList', oldArr)
						this.$store.commit('SET_POWER', true)
						uni.setStorageSync('CHANGE_STUDENT', true) // 切换学员用于控制作业列表页的筛选项
						this.GetUserInfo()
						setTimeout(() => {
							if (this.to == 2) {
								uni.redirectTo({
									url: '/pages/material/index'
								})
							} else if (this.to == 1) {
								apiGetUserInfo().then((res) => {
									if (res.code == '200') {
										this.myInfo = res.data
										if (this.myInfo.defaultClassCode) {
											this.getSettingFlag(this.myInfo.defaultClassCode).then(
												(res) => {
													if (res.reciteFlag == 1) {
														uni.redirectTo({
															url: 'pages/words/index'
														})
													} else {
														uni.redirectTo({
															url:
																'/pages/words/doPlan?classCode=' +
																this.myInfo.defaultClassCode
														})
													}
												}
											)
										} else {
											this.getClassInfo(studentCode).then((res) => {
												if (res) {
													this.getSettingFlag(res.classCode).then(
														(demand) => {
															uni.redirectTo({
																url:
																	'/pages/words/doPlan?classCode=' +
																	res.classCode
															})
														}
													)
												} else {
													uni.redirectTo({
														url: '/pages/words/class'
													})
												}
											})
										}
									}
									// console.log('myInfo',this.myInfo)
								})
							} else if (this.to == 9) {
								//从哪来的回跳哪里去
								let url = uni.getStorageSync('origin')
								uni.setStorageSync('origin', '')
								uni.redirectTo({
									url: url
								})
							} else if (this.to == 3) {
								//课后反馈 班级页面点击学员过来的 对应的逻辑处理
								this.getUserInfoData()
							} else if (this.listenType) {
								uni.navigateTo({
									url: `/pages/exam/listen?listenType=${this.listenType}`
								})
							} else {
								this.toPage()
							}
						}, 1000)
					} else {
						this.status = 2
						this.msg = res.msg
						setTimeout(() => {
							this.status = 1
						}, 2000)
					}
				})
				.catch((err) => {
					// console.log('mmmm',err)
					this.status = 2
					this.msg = err.msg
					setTimeout(() => {
						this.status = 1
					}, 2000)
				})
		},
		addStudentCode() {
			// 置灰不可点击
			if (!this.addStudentFlag) {
				return
			}
			if (!this.verifyCode) {
				this.errorVerify = '请输入验证码'
				return
			}
			apiGetStudentListByPhone({
				mobile: this.mobile,
				verificationCode: this.verifyCode
			})
				.then((res) => {
					if (res.code == 200) {
						console.log('查询', res)
						if (!res.data || !res.data.length) {
							this.tipText = '该手机号没有学员信息，请重新输入'
							this.count = ''
							this.show = true
							clearInterval(this.timer)
							this.timer = null
							// this.addStudentFlag=false
							return
						}
						// 手机号下只有一个学员直接绑定   否则直接进入多选列表
						if (res.data.length == 1) {
							// 查到当前手机下面在集团里只有一个学员，直接绑定跳走页面、
							// 未添加
							if (!res.data[0].addFlag && !res.data[0].expiredFlag) {
								//未添加 未过期
								// 提示添加成功(默认绑定)/跳转绑定列表页

								this.addBinding(res.data)
								return
							}
							if (!res.data[0].addFlag && res.data[0].expiredFlag) {
								//未添加 已过期过期
								// 提示学员号已过期/还在输手机号的页面
								this.showToastFun('学员号已过期')
								this.count = ''
								this.show = true
								clearInterval(this.timer)
								this.timer = null
								return
							}

							// 已添加
							if (
								res.data[0].addFlag &&
								!res.data[0].expiredFlag &&
								res.data[0].bindFlag
							) {
								//已添加 未过期 已绑定
								// 提示添加成功/跳转绑定列表页
								this.showToastFun('添加成功')
								setTimeout(() => {
									uni.navigateBack()
								}, 2000)
								return
							}
							if (
								res.data[0].addFlag &&
								res.data[0].expiredFlag &&
								res.data[0].bindFlag
							) {
								//已添加 已过期 已绑定
								// 提示学员号已过期/还在输手机号的页面
								this.showToastFun('学员号已过期')
								this.count = ''
								this.show = true
								clearInterval(this.timer)
								this.timer = null
								return
							}
							if (
								res.data[0].addFlag &&
								!res.data[0].expiredFlag &&
								!res.data[0].bindFlag
							) {
								//已添加 未过期 未绑定
								// 提示添加成功 切换绑定状态，跳转绑定列表页
								// this.addBinding(res.data)
								this.bindStudentCode(true, res.data[0].studentCode)
								return
							}
							if (
								res.data[0].addFlag &&
								res.data[0].expiredFlag &&
								!res.data[0].bindFlag
							) {
								//已添加 已过期 未绑定
								// 提示学员号已过期/还在输手机号的页面
								this.showToastFun('学员号已过期')
								this.count = ''
								this.show = true
								clearInterval(this.timer)
								this.timer = null
								return
							}
						} else if (res.data.length > 1) {
							//手机下面在集团里有多个学员
							this.$store.dispatch('setStudentList', res.data)
							uni.navigateTo({
								url: '/pages/bindStudentCode/selectStudentsList'
							})
						}
					} else {
						// this.errorVerify=res.msg
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
				.catch((err) => {
					this.tipText = err.msg
				})
		},
		// 绑定学员
		addBinding(arrList) {
			apiAddBinding(JSON.stringify(arrList))
				.then((res) => {
					console.log('绑定学员', res)
					if (res.code == 200) {
						this.showToastFun('添加成功')
						setTimeout(() => {
							uni.navigateBack()
						}, 2000)
					} else {
						this.showToastFun(res.msg)
					}
				})
				.catch((err) => {
					this.showToastFun(err.msg)
				})
		},
		//换绑
		bindStudentCode(bindFlag, studentCode) {
			let qureyData = {
				bindFlag,
				studentCode
			}
			this.$tip.loading()
			apiBindStudentCode(qureyData)
				.then((res) => {
					this.$tip.loaded()
					if (res.code == 200) {
						this.showToastFun('添加成功')
						setTimeout(() => {
							uni.navigateBack()
						}, 2000)
					} else {
						uni.showToast({
							title: res,
							icon: 'none',
							duration: 2000
						})
					}
				})
				.catch((error) => {
					this.$tip.loaded()
					this.$tip.confirm(error.msg, false)
				})
		},
		getUserInfo() {
			apiGetUserInfo().then((res) => {
				if (res.code == '200') {
					this.myInfo = res.data
				}
			})
		},
		// 吐司
		showToastFun(text) {
			uni.showToast({
				title: text,
				icon: 'none',
				duration: 2000
			})
		},
		getSettingFlag(studentCode) {
			return new Promise((resolve, reject) => {
				let data = { common: {} }
				data.common.classCode = studentCode
				apiSelectBooksByClassCode(data)
					.then((res) => {
						if (res.code == 200) {
							resolve(res.data) // res.data.reciteFlag
						} else {
							reject(err)
						}
					})
					.catch((err) => {
						reject(err)
					})
			})
		},
		// 获取绑定的学员
		getUserInfoData() {
			// 查询绑定的学员接口
			apiGetUserInfo().then((res) => {
				if (res.code == '200') {
					// 判断绑定的学员和我从班级反馈点击过来的学员是否一致
					if (res.data.defaultStudentCode == this.feedbackData.studentCode) {
						// 一致  进入学员反馈页面
						uni.setStorageSync('origin', this.backUrl)
						uni.reLaunch({
							url:
								'/pages/work/feedback?instanceId=' +
								this.feedbackData.instanceId +
								'&instanceStudentId=' +
								this.feedbackData.instanceStudentId +
								'&isNew=' +
								this.feedbackData.isNew +
								'&studentCode=' +
								this.feedbackData.studentCode +
								'&isComplete=' +
								this.feedbackData.isComplete
						})
					} else {
						// 不一致进入班级反馈页面
						uni.reLaunch({
							url: this.backUrl
						})
					}
				}
			})
		},
		getClassInfo(studentCode) {
			//获取班级列表
			return new Promise((resolve, reject) => {
				let query = {
					studentCode: studentCode,
					userId: this.myInfo.userId
				}
				apiMyClassByStudentCode(query)
					.then((res) => {
						let hasCurrentPlan = false
						if (res.code == 200) {
							let classItems = res.data
							// classItems.map((item,index)=>{
							// 	if(item.currentPlan && classItems.length == 1){
							// 		hasCurrentPlan = true
							// 	}
							// })
							if (classItems.length == 1) {
								if (classItems[0].currentPlan) {
									hasCurrentPlan = true
									resolve(classItems[0])
								}
							}
							resolve(hasCurrentPlan)
						}
						resolve(hasCurrentPlan)
					})
					.catch((err) => {
						console.log(err)
					})
			})
		},
		// 跳转到指定页面
		toPage() {
			if (uni.getStorageSync('origin')) {
				let url = uni.getStorageSync('origin')
				uni.setStorageSync('origin', '')
				uni.redirectTo({
					url: url
				})
			} else {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		},
		// 跳转至绑定邮箱
		goBindEmail() {
			if (!this.isTeacher) {
				if (
					this.myInfo.defaultStudentCode &&
					(this.myInfo.virtualMobile == '' || !this.myInfo.virtualMobile)
				) {
					uni.showToast({
						title: '您已绑定学员号，请解绑后操作',
						icon: 'none'
					})
				} else {
					uni.redirectTo({
						url: '/pages/user/bindEmail'
					})
				}
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.backgrounCont {
	width: 100%;
	padding: 0 8%;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	box-sizing: border-box;
	overflow: hidden;
}

.prompt_copy {
	color: #ff4546;
	font-size: 32rpx;
}
.isHide {
	display: none !important;
}

input::placeholder {
	font-size: 32rpx;
}

.bind_stu {
	margin-top: 15%;
	.title_row {
		font-size: 46rpx;
		color: #333333;
	}

	.name_row {
		// position: relative;
		width: 100%;
		margin-bottom: 70rpx;

		.username {
			font-size: 32rpx;
			margin-top: 23%;
		}

		.clear_name {
			position: absolute;
			right: 0;
			bottom: 30rpx;
			font-size: 32rpx;
		}

		.tit_text {
			margin-bottom: 5%;
			font-size: 24rpx;
			color: red;
			height: 2rpx;
			// background-color: red;
		}
	}

	.pwd_row {
		// position: relative;
		width: 100%;

		.password {
			font-size: 32rpx;
			width: 340rpx;
		}

		.clear_pwd {
			position: absolute;
			left: 340rpx;
			bottom: 20rpx;
			font-size: 32rpx;
		}

		.tit_text {
			margin-bottom: 5%;
			font-size: 24rpx;
			color: red;
			height: 2rpx;
		}
		.get_code {
			font-size: 28rpx;
			color: #0bc285;
			// background-color: #0BC285;
			width: 200rpx;
			height: 80rpx;
			text-align: center;
			line-height: 80rpx;
			position: absolute;
			right: 0;
			bottom: 6rpx;
		}
	}

	input {
		display: inline-block;
		border: none;
		width: 87%;
		height: 70rpx;
	}

	.add_btn {
		margin-top: 20%;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 88rpx;
		background: #0bc285;
		border-radius: 41rpx;
		color: #ffffff;
		font-size: 32rpx;
	}
}

.prompt-box {
	display: none;
	position: fixed;
	top: 0;
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 100%;
	z-index: 2;
	.alert_prompt {
		display: flex;
		text-align: center;
		align-items: center;
		flex-flow: column;
		flex-wrap: wrap;
		width: 60%;
		height: 15%;
		background: #313131;
		border-radius: 14rpx;

		.prompt_icon {
			margin-top: 7%;
			width: 40rpx;
			height: 40rpx;
			color: #ffffff;
			font-size: 64rpx;
		}

		.prompt_text {
			font-size: 24rpx;
			margin-top: 7%;
			color: #ffffff;
		}
	}
}
.jump-url {
	margin-top: 40rpx;
	padding: 0 8%;
	.url-link {
		color: #0bc285;
		display: inline-block;
	}
}
</style>
